package com.powernode.controller;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.powernode.domain.MemberCollection;
import com.powernode.domain.Prod;
import com.powernode.model.Result;
import com.powernode.service.MemberCollectionService;
import com.powernode.util.AuthUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

/**
 * @create: 2024/7/24
 * @author: gyhe10
 * @description: 会员收藏商品业务控制层
 **/

@Api(tags = "会员收藏商品业务接口管理")
@RestController
@RequestMapping("p/collection")
public class MemberCollectionController {

    @Resource
    private MemberCollectionService memberCollectionService;

    /**
     * 查询会员收藏商品的数量
     * @return
     */
    @ApiOperation("查询会员收藏商品的数量")
    @GetMapping("count")
    public Result<Long> loadMemberCollectionCount() {
        Long count = memberCollectionService.queryMemberCollectionCount();
        return Result.success(count);
    }

    /**
     * 分页查询会员收藏的商品列表
     * @param current 当前页码
     * @param size 每页显示记录数
     * @return
     */
    @ApiOperation("分页查询会员收藏的商品列表")
    @GetMapping("prods")
    public Result<Page<Prod>> loadMemberCollectionProdPage(@RequestParam Long current,
                                                           @RequestParam Long size) {
        Page<Prod> page = memberCollectionService.queryMemberCollectionProdPage(current, size);
        return Result.success(page);
    }

    /**
     * 小程序查询会员收藏商品状态
     * @param prodId 商品id
     * @return
     */
    @ApiOperation("小程序查询会员收藏商品状态")
    @GetMapping("isCollection")
    public Result<Boolean> loadMemberIsCollection(@RequestParam Long prodId) {
        // 获取当前会员的openId
        String openId = AuthUtils.getMemberOpenId();
        MemberCollection memberCollection = memberCollectionService.getOne(new LambdaQueryWrapper<MemberCollection>()
                .eq(MemberCollection::getOpenId, openId)
                .eq(MemberCollection::getProdId, prodId));
        // 判断会员是否收藏了该商品，不为空表示已收藏
        return Result.success(ObjectUtil.isNotNull(memberCollection));
    }

    /**
     * 添加或取消收藏商品
     * @param prodId 商品id
     * @return
     */
    @ApiOperation("添加或取消收藏商品")
    @PostMapping("addOrCancel")
    public Result<String> addOrCancelMemberCollection(@RequestBody Long prodId) {
        // 获取当前用户的openId
        String openId = AuthUtils.getMemberOpenId();
        Boolean flag = memberCollectionService.addOrCancelMemberCollection(openId, prodId);
        return Result.handle(flag);
    }


}
